package com.fizz.redpacket.lock;

import com.fizz.redpacket.lock.LockKey;
/*    */ import com.fizz.redpacket.lock.RedisLock;
/*    */ import java.util.UUID;
/*    */ import java.util.concurrent.TimeUnit;
/*    */ import org.springframework.data.redis.core.RedisTemplate;
/*    */ import org.springframework.data.redis.core.ValueOperations;

public class MyRedisLock extends RedisLock {

    ThreadLocal<String> threadLocal;
    public MyRedisLock(RedisTemplate<String, Object> template, long expired) {
        super(template, expired);
        this.threadLocal = new ThreadLocal<>();
    }

    public void lock() {
        throw new UnsupportedOperationException();
    }


    public boolean tryLock() {
        throw new UnsupportedOperationException();
    }

    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        throw new UnsupportedOperationException();
    }

    public boolean tryLock(String userId, String redPacketId) {
        String lockKey = LockKey.getLockKey(userId, redPacketId);
        long expireTime = this.expired;
        String value = UUID.randomUUID().toString();
        ValueOperations<String, Object> operations = this.template.opsForValue();
        boolean isLock = operations.setIfAbsent(lockKey, value, expireTime, TimeUnit.SECONDS).booleanValue();
        return isLock;
    }

    public void unlock(String userId, String redPacketId) {
        String lockKey = LockKey.getLockKey(userId, redPacketId);
        String actualValue = (String)this.template.opsForValue().get(lockKey);
        String expectValue = this.threadLocal.get();
        if (actualValue == null || expectValue == null) {
            return;
        }

        if (actualValue.equals(expectValue)) {
            this.template.delete(lockKey);
            this.threadLocal.remove();
        }
    }

     public void unlock() {
        throw new UnsupportedOperationException();
    }
}
